package cn.cuilan.client.core;

import cn.cuilan.common.core.ProtocolMessageListener;
import cn.cuilan.common.entity.ProtocolMessage;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

/**
 * 客户端消息处理器
 *
 * @author zhnag.yan
 */
@Slf4j
@Component
public class NetClientMessageProcessor implements ProtocolMessageListener<ProtocolMessage> {

    private CountDownLatch countDownLatch;

    private volatile ProtocolMessage responseMessage;

    @Override
    public boolean applies(ProtocolMessage protocolMessage) {
        return true;
    }

    @Override
    public boolean onMessage(ChannelHandlerContext ctx, ProtocolMessage message) {
        log.info("客户端收到响应.");

        this.responseMessage = message;

        countDownLatch.countDown();
        return false;
    }

    public void reset() {
        countDownLatch = new CountDownLatch(1);
    }

    public ProtocolMessage waitMsg() {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }
}
